programming4us
           
 
 
SQL Server

SQL Server 2008 : Viewing and Modifying Data (part 3) - Creating Functions and Creating Triggers

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
10/17/2010 5:40:10 PM

Creating Functions

Functions, like stored procedures, are saved Transact-SQL statements. Unlike stored procedures, functions cannot perform actions by executing DML statements. Functions always return a single value or a single table-valued expression. They are used by database developers to encapsulate and reuse calculations. For example, you may create a function to calculate the tax amount given a particular salary or to determine whether an e-mail address that has been provided is valid.

It is possible for a function to take no parameters, but often functions accept multiple input parameters and use the parameter values in the calculations which the particular function represents. Unlike stored procedures, functions do not support output parameters. The following types of functions are available within SQL Server 2008:

  • Scalar functions These functions return a single value of any data type.

  • Single statement table-valued functions These functions execute a single SELECT statement and return the result of this statement as a table-valued expression.

  • Multiple statement table-valued functions These functions return several table-valued expressions created by one or more SELECT statements.

  • Built-in functions SQL Server provides many built-in functions to perform common tasks. For example, the GETDATE() built-in function returns today’s date and time. The AVG() function returns the average value of the column.

You can use the CREATE FUNCTION statement to create new functions using the syntax shown in Example 5. You can use the ALTER FUNCTION statement to change the function’s definition.

Example 5. Create Function Statement—Syntax
CREATE FUNCTION [schema_name].function_name (
[@parameter1_name parameter1_data_type [=default_parameter_value],
[@parameter2_name parameter2_data_type...])
RETURNS data_type
AS
transact_sql_statements

Example 6 demonstrates how to create and use scalar and table-valued functions.

Example 6. Working with Functions
CREATE FUNCTION ConvertKilogramsToPounds
(@Kilograms decimal(18,2))
RETURNS decimal(18,2)
AS
BEGIN
DECLARE @Pounds decimal (18,2)
SET @Pounds = @Kilograms * 2.21
RETURN (@Pounds)
END
PRINT dbo.ConvertKilogramsToPounds(5)
-- Results:
-- 11.05

Creating Triggers

Triggers are stored procedures that are bound to a table or view. They run when a DML statement is executed on the table or view. You can specify triggers as FOR UPDATE, FOR INSERT, and FOR DELETE. These triggers will execute immediately after INSERT, UPDATE, or DELETE operations. You can also create INSTEAD OF UPDATE, INSTEAD OF INSERT, and INSTEAD OF DELETE triggers. These triggers will execute without the data being actually inserted, updated, or deleted.

A trigger can query tables and views, execute DML statements, and include complex Transact-SQL logic. The trigger and DML statement that caused the trigger to fire occur within the context of a single transaction. It is possible to roll back INSERT, UPDATE, and DELETE statements from within a trigger. This is useful for complex data validation purposes. You can use triggers to manually cascade changes through related tables; to guard against malicious or incorrect INSERT, UPDATE, and DELETE operations; and to enforce other restrictions that are more complex than those defined by using CHECK constraints.

Exam Warning

Triggers should be used sparingly because they have severe performance implications. In addition, triggers can be difficult to maintain.


Unlike CHECK constraints, triggers can reference columns in other tables. For example, a trigger can use a SELECT statement from another table to compare to the inserted or updated data and to perform additional actions, such as modifying the data or displaying a user-defined error message. Triggers can evaluate the state of a table before and after a data modification and take actions based on that difference. Multiple triggers of the same type (INSERT, UPDATE, or DELETE) on a table allow multiple different actions to take place in response to the same modification statement. Triggers also allow the use of custom error messages.

Triggers can be specified as FOR, AFTER, or INSTEAD OF. The trigger action will fire during the DML statement, after the DML statement, or in place of the DML statement, respectively. Triggers can be specified for UPDATE, INSERT, DELETE, or any combination of these.

How do you know what data the user is attempting to insert, update, or delete within a trigger? The trigger can access special tables called INSERTED and DELETED. These virtual tables exist only while the trigger is executing. The INSERTED table contains the new values you are attempting to insert into the table, or new values of the row when you are attempting to update data. The DELETED table contains the row you are attempting to delete or old values of the row when you are attempting to update data. Make use of these tables by querying them to determine old and new values of the data being affected. To cancel the DML statement from within a trigger and roll it back, use the ROLLBACK TRANSACTION statement.

Example 7 demonstrates how to create triggers, and the effect they take after a DML statement is executed on the table to which the trigger is bound.

Example 7. Creating a Trigger on the Stars Table
CREATE TABLE StarHistory
(StarHistoryId int IDENTITY PRIMARY KEY, StarName varchar(50), OldType ntext,
NewType ntext, DateChanged DateTime);
GO
CREATE TRIGGER UpdateStarHistory
on dbo.Stars
AFTER INSERT, UPDATE
AS
BEGIN
INSERT StarHistory (StarName, OldType, NewType, DateChanged)
SELECT INSERTED.StarName, DELETED.StarType, INSERTED.StarType, GETDATE()
FROM INSERTED LEFT JOIN DELETED on INSERTED.StarID = DELETED.StarID
END
GO

UPDATE Stars SET StarType = 'Burnt out' WHERE StarName = 'Sun';
GO
SELECT * FROM StarHistory
-- Results:
-- StarHistoryId StarName OldType NewType DateChanged
-- ------------- ---------- ---------- ----------- ---------------
-- 1 Sun Yellow dwarf Burnt out 2009-01-21
11:56:29.530


Other -----------------
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us